<template>
  <div class="user-header">
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-form :model="formsearch" :inline="true">
      <el-form-item>
        <el-input v-model.trim="formsearch.keyword" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSerch">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table :data="list" style="width: 100%" height="500px">
      <el-table-column v-for="item in tableLabel" :key="item.prop" :label="item.label" :prop="item.prop" :width="item.width ? item.width : 125" />

      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination small background layout="prev, pager, next" :total="config.total" @current-change="changePagre" class="pager" />
  </div>
  <el-dialog v-model="dialogVisible" :title="action === 'add' ? '新增用户' : '编辑用户'" width="35%" :before-close="handleClose">
    <el-form :model="formuser" :inline="true" ref="userForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name" :rules="[
            {required:true,message:'姓名是必填的'}
          ]">
            <el-input v-model="formuser.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age" :rules="[
            {required:true,message:'年龄是必填的'},
            {type:'number',message:'年龄必须是数字'}
          ]">
            <el-input v-model.number="formuser.age" placeholder="请输入年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓别" prop="sex" :rules="[
            {required:true,message:'请选择性别'}
          ]">
            <el-select v-model="formuser.sex" placeholder="请选择">
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birth" :rules="[
            {required:true,message:'请选择出生日期'}
          ]">
            <el-date-picker value-format="YYYY-MM-DD" v-model="formuser.birth" type="date" placeholder="请选择" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="地址" prop="addr" :rules="[
            {required:true,message:'地址是必填的'}
          ]">
        <el-input v-model="formuser.addr" placeholder="请输入地址" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import { getCurrentInstance, onMounted, defineComponent, ref, reactive } from 'vue'

export default defineComponent({
  setup() {
    const { proxy } = getCurrentInstance()
    // ref里面的内容用到的时候需要添加.value才能使用,dom上则可以直接使用
    const list = ref([])
    //表头设置
    const tableLabel = reactive([
      {
        prop: 'name',
        label: '姓名'
      },
      {
        prop: 'age',
        label: '年龄'
      },
      {
        prop: 'sexLabel',
        label: '性别'
      },
      {
        prop: 'birth',
        label: '出生日期',
        width: 200
      },
      {
        prop: 'addr',
        label: '地址',
        width: 320
      }
    ])
    onMounted(() => {
      getUser(config)
    })
    const config = reactive({
      total: 0,
      page: 1,
      name: ''
    })
    //用户列表数据
    const getUser = async config => {
      let res = await proxy.$api.getUserData(config)
      config.total = res.count
      list.value = res.list.map(item => {
        item.sexLabel = item.sex === 0 ? '女' : '男'
        return item
      })
    }
    // 改变用户列表时触发
    const changePagre = page => {
      config.page = page
      getUser(config)
    }

    //双向绑定用reactive
    const formsearch = reactive({
      keyword: ''
    })
    //搜索用户
    const handleSerch = () => {
      if (!formsearch.keyword) {
        return ElMessage({
          showClose: true,
          message: '用户名不能为空',
          type: 'error'
        })
      }
      config.name = formsearch.keyword
      getUser(config)
    }
    // 控制模态框的显示隐藏
    const dialogVisible = ref(false)
    //点击模态框右上的关闭按钮
    const handleClose = done => {
      ElMessageBox.confirm('确定关闭吗?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          //清空表单
          proxy.$refs.userForm.resetFields()
          done()
        })
        .catch(() => {
          // catch error
        })
    }
    //添加用户的form表单数据
    const formuser = reactive({
      name: '',
      age: '',
      sex: '',
      birth: '',
      addr: ''
    })
    //确认添加和编辑用户
    const onSubmit = () => {
      proxy.$refs.userForm.validate(async valid => {
        if (valid) {
          if (action.value == 'add') {
            //新增的接口
            let res = await proxy.$api.addUser(formuser)
            if (res) {
              //清空表单
              proxy.$refs.userForm.resetFields()
              //关闭模态框
              dialogVisible.value = false
              getUser(config)
            }
          } else {
            // formuser.sex === '男' ? (formuser.sex = 'nan') : (formuser.sex = 0)
            //编辑的接口
            let res = await proxy.$api.editUser(formuser)
            console.log(res);
            if (res) {
              //清空表单
              proxy.$refs.userForm.resetFields()
              //关闭模态框
              dialogVisible.value = false
              getUser(config)
            }
          }
        } else {
          ElMessage({
            showClose: true,
            message: '请填写完善用户信息',
            type: 'error'
          })
        }
      })
    }
    //取消添加或编辑用户
    const handleCancel = () => {
      //清空表单
      proxy.$refs.userForm.resetFields()
      //关闭模态框
      dialogVisible.value = false
    }
    //区分编辑和新增
    const action = ref('add')
    //点击编辑按钮
    const handleEdit = row => {
      // console.log(row);
      action.value = 'edit'
      dialogVisible.value = true
      row.sexLabel === '男' ? (row.sex = '男') : (row.sex = '女')
      //解决点击编辑关闭之后，再点击新增按钮form表单还包含编辑时的用户信息
      proxy.$nextTick(() => {
        //浅拷贝
        Object.assign(formuser, row)
      })
    }
    //点击新增按钮
    const handleAdd = () => {
      dialogVisible.value = true
      action.value = 'add'
    }
    //点击删除按钮
    const handleDelete = row => {
      ElMessageBox.confirm('确定删除吗?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await proxy.$api.deletUser({
            id: row.id
          })
          ElMessage({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
          getUser(config)
        })

        .catch(() => {
          // catch error
        })
    }
    return {
      list,
      tableLabel,
      config,
      changePagre,
      formsearch,
      handleSerch,
      dialogVisible,
      handleClose,
      formuser,
      onSubmit,
      handleCancel,
      handleEdit,
      action,
      handleAdd,
      handleDelete
    }
  }
})
</script>

<style lang="less" scoped>
.table {
  position: relative;
  height: 520px;
  .pager {
    position: absolute;
    right: 0;
    bottom: -20px;
  }
}
.user-header {
  display: flex;
  justify-content: space-between;
}
</style>